<template>
  <div class="main">
    <tabs :defaultTagId="defaultTagId" :custom="false" :tabPaneData="tabPaneData" @change="callback"></tabs>
    <div class="styleTabsMain">
      <div id="baseInfo" class="headMain">
        <div class="headTitle">
          <div class="processName">{{ deliverableName }} </div>
        </div>
        <div style="padding-top: 4px;">
          <div v-if="basicInformation.length !== 0">
            <div class="messageContent" v-for="(item, index) in basicInformation" :key="index">
              <div v-for="item1 in item.items" :class="item1.length==1?'message_de':'message_deOne'"
                  :key="item1.id">
                <detailMessage :attrList="item1"></detailMessage>
              </div>
            </div>
          </div>
          <a-empty v-else description="暂无数据" class="nodata"/>
          <h5 v-if="showFileLists.length" style="margin-top:20px;">相关附件：</h5>
          <a-spin :spinning='loadTable' v-if="showFileLists.length">
            <common-table :isRowsSelectVisible="false" :isPagination="false" :scrollx="false" :columnWidth="20" :columns="tableColumns" :tableData="showFileLists" @routerPage="routerPage"></common-table>
          </a-spin>
        </div>
      </div>
      <div id="associatedTaskBook" class="associatedTaskBook">
        <div class="titleBox">
          <span class="title">关联的项目任务书</span>
          <!-- <a-button type="primary">
            修订项目任务书
          </a-button> -->
        </div>
        <div class="tableContent">
          <a-empty description="暂无数据" class="nodata"/>
          <!-- <attachment :bookOid="bookOids" :bookVersion="bookVersions" typeFrom="1" @onlyOne="onlyOneHandle" @selectedData="selectedData"></attachment> -->
        </div>
      </div>
      <div id="processSet" class="processSet"> 
        <div class="titleBox">
          <span class="title">流程设置</span>
          <a-button type="primary" v-if="isShowSponsor" @click="openDraw">以起草人身份操作</a-button>
        </div>
        <div class="main">
          <div class="process-explain">
            流程说明： <br>
            一、不可控因素“十二条”：<br>
            1、 客户或市场需求变化；<br>
            2、 大生产期间优先保供（需所在单位第一负责人确认）；<br>
            3、 客户试用验证受阻（集团外部客户：需营销公司总经理确认；集团内部客户：需求提出方的研究院院长确认）；<br>
            4、集团内配套零部件项目或主机项目延期造成对方影响（零部件与主机开发必须分属不同研究院，由对方研究院长确认）；<br>
            5、 国家/行业/地方政策、标准、法律法规变化；<br>
            6、 国家检测机构因素；<br>
            7、 自然灾害；<br>
            8、 天气变化；<br>
            9、 意外事故；<br>
            10、长周期外购件供应商未按合同要求供货（需商务或质保部第一负责人确认）；<br>
            11、出口发运周期变化（需发运部门第一负责人确认）；<br>
            12、其余研发管理总部确认的不可控因素。<br>
            二、实施要求：<br>
            1、因不可控因素“十二条”造成研发项目（或节点）延期超过1个月或总开发周期的1/5时，方可调整项目（或节点）完成时间。除此之外，不允许调整项目（或节点）完成时间；<br>
            2、所有项目延期申请需按要求附上相应的证明材料（如各相关部门负责人对延期原因确认的签字文件等），或在事业部审批节点中增加对应部门负责人审批节点。<br>
            <br>
          </div>
          <processComp bookRouterTitle="变更流程" :isUser="isUser" :stepArr="stepArr" :objOid="changeOid"></processComp>
        </div>
      </div>
    </div>
    <!--    操作按钮的弹框集合-->
    <!--    以起草人身份操作抽屉-->
    <comm-el-process-handle v-if="isShowProcessHandle" @closeDraws="closeDraws" :reviewId="changeOid" @commitApplyComplete="closeDraws"></comm-el-process-handle>
  </div>
</template>
 
<script>
import tabs from "@/components/tabs/tabs"
// import attachment from '../../projectTaskBook/mainTaskBook/attachment'
import processComp from "./processComp"
import detailMessage from "@/components/singlePage/detailMessage";
import { saveFile } from '@/utils/util'
import commElFilestartUpload from '@/views/singleProject/fileSingle/el-common/comm-el-filestart-upload'//添加交付物模态框
import commonProcessSettings from '@/components/common/commonProcessSettings'//流程处理选择人员（修改）
import commonProcess from '@/components/processCommon/approveProcess'
import approveFrom from '@/components/processCommon/createProcess/approveFrom'
import commonTable from '@/components/common/commonTable'
import commModal from "@/views/singleProject/fileSingle/el-common/comm-modal";
import taskTable from "@/views/plmHomePage/toDoPage/comp/taskTable.vue";
import commElProcessHandle from './comm-el-processHandle'//以起草人身份操作
import { getTaskBookByProject, TaskBookAttachmentInfo, downloadAttachmentFile } from '@/api/taskBook';
import {
  getDisplayIdentifier, getAttributeGroup, getProcessSteps, getDisposeStatus
} from "@/api/fileSingle.js"
let userInfo = JSON.parse(sessionStorage.getItem('userInfo'))
import _ from 'lodash'
export default {
  data() {
    return {
      userinfo: JSON.parse(sessionStorage.getItem('userInfo')),//用户信息
      processName: '',
      deliverableName: '',
      basicInformation: [],
      isShowHistoryVerion: false,
      defaultTagId: 'baseInfo',
      spinning:false,
      tabPaneData: [
        {
          tagId: 'baseInfo',
          tagName: '基本信息',
        
        },
        {
          tagId: 'associatedTaskBook',
          tagName: '关联的项目任务书',
        },
        {
          tagId: 'processSet',
          tagName: '流程设置',
        },
      ],
      bookOids: '', // 任务书oid
      bookVersions:'', //任务书列表
      attachmentSelect: [], // 项目关联的任务书
      isShowSponsor: false,//是否发起人（起草人）
      isShowProcessHandle: false,//显示以起草人身份操作抽屉
      isShowBottomDescribe: false,//流程处理是否显示
      processTableIsShow: true,//流程记录表格是否显示
      stepArr: [],//流程视图数据
      tableArr: [],//流程记录表格数据
      radioArr: [],//单选框数据
      showFileLists:[],//文件列表
      tableColumns: [
        {
          displayName: '文件名',
          name: 'name',
          key: 'name',
          scopedSlots: {
            customRender: "name"
          }
        },
        {
          displayName: '上次修改时间',
          name: 'updateTime',
          key: 'updateTime',
          fieldType: 'Date',
          dataType: 'String',
          scopedSlots: {
            filterDropdown: "filterDropdown",
            filterIcon: "filterIcon",
            customRender: "customRender"
          }
        },
        {
          displayName: '创建者',
          name: 'updater',
          key: 'updater'
        }
      ],
      loadTable: false,
      isUser:"false",
      stateDisPlay:'',
      changeOid:'',
    }
  },
  components: {
    tabs,
    // attachment,
    processComp,
    detailMessage,
    commonProcessSettings,
    commonProcess,
    commModal,
    approveFrom,
    commonTable,
    taskTable,
    commElFilestartUpload,
    commElProcessHandle
  },
  created() {
  },
  computed: {
  },
  watch:{
  },
  destroyed(){
    this.defaultTagId = 'baseInfo'
  },
  mounted() {
      this.oid = sessionStorage.getItem('oid')
      this.userId = userInfo.loginName
      this.changeOid = sessionStorage.getItem('changeOid')
      // sessionStorage.setItem("reviewId",this.changeOid)
      this.isUser = this.$route.query.creator;//是否为创建者//登录和创建是同一个人才有催一下
      this.stateDisPlay = this.$route.query.stateDisPlay;
      this._getTaskBookByProject() // 获取任务书oid
      // this.currentOid = "VR:wt.doc.WTDocument:4094104"
      this.currentOid = this.changeOid
      this._getDisplayIdentifier()
      this._getAttributeGroup()
      this._getProcessSteps()
      this._TaskBookAttachmentInfo();
      // this._getDisposeStatus()
  },
  methods: {
    /**
     * commonProcessSettings 组件回调方法
     * 功能： 提交审核人
     */
    // 表格数据
    _getTaskBookByProject() {
      getTaskBookByProject({ oid: `OR:com.pisx.pmgt.project.PIProject:${this.oid}`, userId: this.userId }).then(({data}) => {
        if (data.success) {
          if (data.data && data.data.length) {
            this.bookOids = data.data[0].bookOid;
            this.bookVersions = data.data[0].version;
          } else {
            this.$message.info(data.message || '暂无任务书数据')
          }
        }
      })
    },
    //查看附件
    _TaskBookAttachmentInfo() {
      this.loadTable = true
      TaskBookAttachmentInfo({ oid: this.changeOid, userId: this.userId }).then(({data}) => {
        this.loadTable = false
        if (data.success) {
          if (data.data && data.data.length) {
            this.showFileLists = data.data;
            if (this.showFileLists.length === 1) {
              this.$emit('onlyOne', this.tableData)
            }
          } else {
            this.showFileLists = []
          }
        }else{
          this.showFileLists = []
          this.$message.error(data.message)
        }
      })
    },
    //预览附件
    routerPage(rows) {
      let name = rows.name;
      let str = name.substring(name.lastIndexOf(".")+1);
      let paramInfo = { userId: this.userId, oid: rows.oid }
      downloadAttachmentFile(paramInfo).then(resultInfo => {
        if (resultInfo && resultInfo.status === 200) {
          const blob = new Blob([resultInfo.data], {type: `application/${str}`})
          saveFile(blob, name)
        } else {
          this.$message.warn('导出异常')
        }
      })
    },
    _getAttributeGroup() {
      let obj = JSON.parse(sessionStorage.getItem('changeVal'));
      let newArr = [{
        items:[{
          label:'名称',
          value:obj.name
        },{
          label:'编码',
          value:obj.number
        }]
      },{
        items:[{
          label:'变更类别',
          value:obj.ChangeCategory
        },{
          label:'申请延期时间',
          value:obj.DelayDate
        }]
      },{
        items:[{
          label:'所属阶段',
          value:obj.planActivityReference
        },{
          label:'执行现状',
          value:obj.StatusOfImplementation
        }]
      },{
        items:[{
          label:'变更理由',
          value:obj.ReasonForChange
        },{
          label:'变更对项目的影响',
          value:obj.ChangeImpact
        }]
      },{
        items:[{
          label:'具体变更内容-变更前',
          value:obj.BeforeChange
        },{
          label:'具体变更内容-变更后',
          value:obj.AfterChange
        }]
      },{
        items:[{
          label:'负责人',
          value:obj.responsibleUserReference
        },{
          label:'是否剔除考核',
          value:obj.EliminateAppraisal
        }]
      },{
        items:[{
          label:'状态',
          value:obj.stateDisPlay
        }]
      }]
      this.basicInformation = newArr;
      return false;
      //基本信息
      getAttributeGroup({oid: this.currentOid}).then((resultInfo) => {
        if (resultInfo && resultInfo.status === 200) {
          if (resultInfo.data && resultInfo.data.success) {
            if (resultInfo.data.data.length > 0) {
              this.basicInformation = resultInfo.data.data[0].rows
            } else {
              this.basicInformation = []
            }
          } else {
            this.basicInformation = []
            this.$message.error(resultInfo.data.message)
          }
        } else {
          this.$message.error('接口失败！')
        }
      })
    },
    _getDisplayIdentifier() {
      getDisplayIdentifier({oid:this.currentOid}).then((resultInfo) => {
        if (resultInfo && resultInfo.data && resultInfo.status === 200) {
          if (resultInfo.data.success) {
            // 去掉标题的状态字符 入 A.1-审核，去掉 -审核
            let str = resultInfo.data.message.slice(resultInfo.data.message.length-3,-2)
            if(str=='-'){
              this.deliverableName = resultInfo.data.message.substring(-1,resultInfo.data.message.length-3)
            }else{
               this.deliverableName = resultInfo.data.message
            }
          } else {
            this.deliverableName = ''
            this.$message.error('操作错误')
          }
        } else {
          this.$message.error('接口失败！')
        }
      })
    },
    _getProcessSteps() {
      this.stepArr = [{"name":"提交","userFullName":"王志伟","stateDisplay":"已关闭","oid":"","state":"closed","runningTime":"","order":"0"},{"name":"初审","userFullName":"王志伟","stateDisplay":"正在运行","oid":"OR:wt.workflow.definer.WfAssignedActivityTemplate:26897819843","state":"open_running","runningTime":"0天22小时28分钟","order":"1"},{"name":"审核","userFullName":"王志伟","stateDisplay":"","oid":"OR:wt.workflow.definer.WfAssignedActivityTemplate:26897819816","state":"","runningTime":"","order":"2"},{"name":"院批准","userFullName":"王志伟","stateDisplay":"","oid":"OR:wt.workflow.definer.WfAssignedActivityTemplate:26897820267","state":"","runningTime":"","order":"4"},{"name":"研发管理部批准","userFullName":"王志伟","stateDisplay":"","oid":"OR:wt.workflow.definer.WfAssignedActivityTemplate:26897819806","state":"","runningTime":"","order":"5"},{"name":"执行变更","userFullName":"王志伟","stateDisplay":"","oid":"OR:wt.workflow.definer.WfAssignedActivityTemplate:26897819823","state":"","runningTime":"","order":"9"},{"name":"确认变更结果","userFullName":"王志伟","stateDisplay":"","oid":"OR:wt.workflow.definer.WfAssignedActivityTemplate:26897820257","state":"","runningTime":"","order":"10"}];
      return false;
      // 获取交付物流程节点（流程指引）
      getProcessSteps({oid: this.changeOid}).then((resultInfo) => {
        if (resultInfo && resultInfo.status === 200) {
          if (resultInfo.data.success) {
            if (resultInfo.data && resultInfo.data.data && resultInfo.data.data !== '' && resultInfo.data.data.length > 0) {
              this.stepArr = resultInfo.data.data.map((item) => {
                item.state = item.state.toLowerCase(); // 统一转化成小写
                return item;
              });
             let arr = resultInfo.data.data.filter((e)=>{
                return e.userFullName !=='';
              })
              this.stepArr = arr
              // 是否显示“起草人..”按钮
              let runStep = resultInfo.data.data[resultInfo.data.data.length - 1]//结束节点的前一个节点
              if (resultInfo.data.data[0].userFullName == this.userinfo.realName && (this.stateDisPlay=='正在审阅' || this.stateDisPlay=='处理中') && runStep.state.indexOf('closed') == -1 ) {
                this.isShowSponsor = true
              } else {
                this.isShowSponsor = false
              }
            } else {
              this.isShowSponsor = false
              this.stepArr = []
            }
          } else {
            this.stepArr = []
            this.$message.error(resultInfo.data.message)
          }
        } else {
          this.$message.error('接口失败！')
        }
      })
    },
    _getDisposeStatus() {
      // 获取交付物流程记录
      getDisposeStatus({oid: this.currentOid}).then((resultInfo) => {
        if (resultInfo && resultInfo.status === 200) {
          if (resultInfo.data && resultInfo.data.success == 'true') {
            if (resultInfo.data.data.length > 0) {
              this.tableArr = _.orderBy(resultInfo.data.data, ['workCompletedDate'], ['desc'])//按照创建时间降序排序
              this.tableArr.splice(0, 0, this.tableArr[this.tableArr.length - 1])      //把最后一个元素复制到首个
              this.tableArr.splice(-1, 1);       //删除最后一个元素
            } else {
              this.tableArr = []
            }
          } else {
            this.tableArr = []
            this.$message.error(resultInfo.data.message)
          }
        } else {
          this.$message.error('接口失败！')
        }
      })
    },
    // 附件只有一行数据回调
    onlyOneHandle(rows) {
      this.attachmentSelect = rows
    },
    // 附件复选框
    selectedData(selects) {
      this.attachmentSelect = select
    },
    callback(keys) {
      this.defaultTagId = keys
      document.querySelector("#" + keys).scrollIntoView();
    },
    // getRoutingIndex 获取流程操作
    getRoutingIndex() {
      getRouting({oid: this.currentOid}).then((resultInfo) => {
        if (resultInfo && resultInfo.status === 200) {
          if (resultInfo.data && resultInfo.data.success) {
            if (resultInfo.data.data && resultInfo.data.data.length > 0) {
              this.radioArr = resultInfo.data.data
            } else {
              this.radioArr = []
            }
          } else {
            this.radioArr = []
            this.$message.error(resultInfo.data.message)
          }
        } else {
          this.$message.error('接口失败！')
        }
      })
    },
  
    /**
     * commElProcessHandle 组件回调方法 功能： 打开抽屉
     */
    openDraw() {
      this.isShowProcessHandle = true
    },
    /**
     * commElProcessHandle 组件回调方法 功能： 关闭抽屉
     * 功能： 关闭抽屉
     */
    closeDraws() {
      this._getProcessSteps()
      this.isShowProcessHandle = false;
    },
  },
};
</script>
<style lang="less" scoped>
  /deep/ .commonTable{
    .ant-table-body{
      min-height: auto;
    }
    .ant-table-placeholder{
      min-height: auto;
      border: none;
    }
  }
</style>
<style lang="less" scoped>
.headMain {
  padding: 20px;
  box-sizing: border-box;
  background-color: #fff;
}
.ant-tabs{
  background-color: #fff;
  border-bottom: 1px solid #ddd;
  padding-top: 10px;
  /deep/.ant-tabs-bar{
    margin: 0;
    padding: 0 25px;
  }
}
.styleTabsMain{
    overflow-y: scroll;
    height: calc(100vh - 100px);
    width: calc(100% + 8px);
    padding-bottom: 85px;
    .associatedTaskBook{
      background-color: #fff;
      margin-top: 21px;
    }
    .processSet{
      background-color: #fff;
      margin-top: 21px;
      .process-explain{
        padding: 0 0 15px 15px;
        font-size: 12px;
        color: #386BD7;
      }
    }
    .titleBox{
      margin-bottom: 15px;
      padding: 15px 0;
      border-bottom: 1px solid #ddd;
      display: flex;
      justify-content: space-between;
      .title{
        color: #333;
        font-size: 18px;
        font-weight: bold;
        padding-left: 15px;
      }
      .ant-btn{
        width: 152px;
        margin-right: 15px;
      }
    }
    .tableContent{
      padding: 0 15px;
    }
    .main{
      padding: 0 15px 15px 15px;
      background-color: #fff;
    }
}
.headTitle {
  display: flex;
  & > p {
    font-size: 20px;
    color: rgba(0, 0, 0, 0.85);
    line-height: 28px;
    font-weight: 500;
  }
}
.basicInformation {
  padding-bottom: 62px;
  display: flex;
  flex-wrap: wrap;
  box-sizing: border-box;
  & > li {
    margin-bottom: 16px;
    width: 33.3%;
    flex-grow: 1;
    & > span:nth-child(1) {
      font-size: 14px;
      color: #666666;
    }
    & > span:nth-child(2) {
      font-size: 14px;
      color: #333333;
    }
    .activeSpan {
      cursor: pointer;
      color: #386bd7 !important;
    }
  }
}
.processName {
  font-size: 20px;
  font-weight: 550;
  color: rgba(0, 0, 0, 0.85);
}
.messageContent {
  width: 100%;
  margin-top: 16px;
  display: flex;
  .message_de {
    width: 30%;
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;
    .messageList {
      min-width: 25%;
      margin: 5px 0;
      font-size: 14px;
      text-align: right;
      display: flex;
      justify-content: flex-start;
    }
  }
  .message_deOne {
    width: 100%;
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;
    .messageList {
      min-width: 25%;
      margin: 5px 0;
      font-size: 14px;
      text-align: right;
      display: flex;
      justify-content: flex-start;
    }
  }
}
</style>